package com.ruoyi.backend.config;


import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class InversionDelayRabbitmqConfig {

    // 延迟队列名称
    public static final String DELAY_QUEUE_NAME = "inversion_result_delay_queue";

    // 延迟交换机名称
    public static final String DELAY_EXCHANGE_NAME = "inversion_result_delay_exchange";

    // 延迟路由键
    public static final String DELAY_ROUTING_KEY = "inversion_result.delay";

    // 死信交换机名称
    public static final String DEAD_LETTER_EXCHANGE = "inversion_result_dead_letter_exchange";

    // 死信路由键
    public static final String DEAD_LETTER_ROUTING_KEY = "inversion_result.process";

    //死信队列
    public static final String DEAD_LETTER_QUEUE = "inversion_result_dead_letter_queue";

    // 延迟时间（1小时 = 3600000毫秒）
    public static final long DELAY_TIME = 60 * 60 * 1000L;


    /**
     * 声明延迟交换机
     */
    @Bean
    public DirectExchange delayExchange() {
        return new DirectExchange(DELAY_EXCHANGE_NAME);
    }

    /**
     * 声明死信交换机
     */
    @Bean
    public DirectExchange deadLetterExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE);
    }

    /**
     * 声明死信队列
     */
    @Bean
    public Queue deadLetterQueue() {
        return new Queue(DEAD_LETTER_QUEUE, true);
    }

    /**
     * 声明延迟队列
     * 该队列没有消费者，消息会在TTL后过期并转发到死信交换机
     */
    @Bean
    public Queue delayQueue() {
        Map<String, Object> arguments = new HashMap<>();
        // 设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        // 设置死信路由键
        arguments.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        // 设置消息过期时间（1小时）
        arguments.put("x-message-ttl", DELAY_TIME);
        return new Queue(DELAY_QUEUE_NAME, true, false, false, arguments);
    }

    /**
     * 死信队列与死信交换机绑定
     */
    @Bean
    public Binding deadLetterBinding() {
        return BindingBuilder.bind(deadLetterQueue())
                .to(deadLetterExchange())
                .with(DEAD_LETTER_ROUTING_KEY);
    }

    /**
     * 延迟队列与延迟交换机绑定
     */
    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue())
                .to(delayExchange())
                .with(DELAY_ROUTING_KEY);
    }



}
